package com.github.shiqiyue.app.api.sapi.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.github.shiqiyue.app.api.sapi.common.SApiBaseController;
import com.github.shiqiyue.app.api.sapi.req.permission.PermissionAddReq;
import com.github.shiqiyue.app.api.sapi.req.permission.PermissionEditReq;
import com.github.shiqiyue.app.api.sapi.result.permission.PermissionTreeDTO;
import com.github.shiqiyue.app.common.constants.GlobalConstants;
import com.github.shiqiyue.app.common.entity.TreeNode;
import com.github.shiqiyue.app.common.enums.EnableEnum;
import com.github.shiqiyue.app.common.result.Result;
import com.github.shiqiyue.app.common.utils.EnumUtil;
import com.github.shiqiyue.app.common.utils.TreeNodeUtils;
import com.github.shiqiyue.app.modules.sys.entity.Permission;
import com.github.shiqiyue.app.modules.sys.enums.PermissionTypeEnum;
import com.github.shiqiyue.app.modules.sys.service.IPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/***
 * 权限控制器
 * @author wenyao.wu
 * @date 2018/10/15
 */
@Slf4j
@Api(tags = "权限")
@RestController
@RequestMapping("sapi/sys/permission")
public class SApiPermissionController extends SApiBaseController {


    @Autowired
    private IPermissionService permissionService;

    /***
     * 权限列表
     * @return
     */
    @PreAuthorize("hasAuthority('0020100')")
    @ApiOperation("权限列表")
    @PostMapping("list")
    public Result<List<TreeNode>> permissionList() {
        // 获取所有有效的权限（按钮）
        List<Permission> permissionList = permissionService.list(new QueryWrapper<Permission>().eq("enable", EnableEnum.ABLE));
        // 转换为vo
        List<PermissionTreeDTO> permissionTreeVOList = permissionList
                .stream()
                .map(item -> PermissionTreeDTO.newInstance(item))
                .collect(Collectors.toList());
        // 添加children属性
        List<TreeNode> treeNodeList = TreeNodeUtils.listToTree(permissionTreeVOList);
        return Result.success(treeNodeList);
    }

    /***
     * 添加权限
     * @param permissionAddDTO
     * @return
     */
    @PreAuthorize("hasAuthority('0020101')")
    @ApiOperation("添加权限")
    @PostMapping("add")
    public Result addPermission(@Valid PermissionAddReq permissionAddDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        if (!permissionAddDTO.getPid().equals(GlobalConstants.TREE_TOP_PID)) {
            Permission parentNode = permissionService.getById(permissionAddDTO.getPid());
            if (PermissionTypeEnum.BUTTON.equals(parentNode.getType())) {
                return Result.fail("按钮下面不能增加节点");
            }
            if (EnableEnum.DISABLE.equals(parentNode.getEnable())) {
                return Result.fail("上级节点无效");
            }
        }
        boolean codeValid = permissionService.isCodeValid(permissionAddDTO.getCode());
        if (!codeValid) {
            return Result.fail("权限编码已存在");
        }
        Permission permission = new Permission();
        permission.setCode(permissionAddDTO.getCode());
        permission.setName(permissionAddDTO.getName());
        permission.setPid(permissionAddDTO.getPid());
        permission.setType(EnumUtil.getEnumByValue(PermissionTypeEnum.values(), permissionAddDTO.getType()));
        permission.setEnable(EnableEnum.ABLE);
        permissionService.save(permission);
        return Result.success();
    }

    /***
     * 修改权限
     * @param permissionEditDTO
     * @return
     */
    @PreAuthorize("hasAuthority('0020102')")
    @ApiOperation("修改权限")
    @PostMapping("edit")
    public Result editPermission(@Valid PermissionEditReq permissionEditDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        boolean codeValid = permissionService.isCodeValid(permissionEditDTO.getCode(), permissionEditDTO.getId());
        if (!codeValid) {
            return Result.fail("权限编码已存在");
        }
        Permission updateParam = new Permission();
        updateParam.setId(permissionEditDTO.getId());
        updateParam.setCode(permissionEditDTO.getCode());
        updateParam.setName(permissionEditDTO.getName());
        permissionService.updateById(updateParam);
        return Result.success();
    }

    /***
     * 删除权限
     * @param id
     */
    @PreAuthorize("hasAuthority('0020103')")
    @ApiOperation("删除权限")
    @PostMapping("delete")
    public Result deletePermission(Long id) {
        permissionService.deleteById(id, true);
        return Result.success();
    }
}
